﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SiteManager.Models;
using SiteManager.Core.Helper;
using System.Data;
using SiteManager.Core.Filters;

namespace SiteManager.Areas.Manager.Controllers
{
    [SiteAdminFilter]
    public class SitesController : Controller
    {
        SiteManagerEntities db = Factorys.Instance.GetEntity();

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public ActionResult Index(int? page, int? row)
        {
            // 获取站点列表
            int r = row ?? ConfigHelper.PageRow;
            int p = page ?? 1;
            List<sites> sites = db.sites.OrderBy(s => s.SiteID).Skip((p - 1) * r).Take(r).ToList();
            return View(sites);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(sites site)
        {
            try
            {
                db.sites.AddObject(site);
                if (db.SaveChanges() > 0)
                {
                    ViewBag.Msg = "操作成功";
                    return RedirectToAction("Index");
                }
            }
            catch(UpdateException error)
            {
                ViewBag.Msg = error.Message;
            }
            return View(site);
        }

        public ActionResult Edit(int id)
        {
            try
            {
                return View(db.sites.Single(s => s.SiteID == id));
            }
            catch
            {
                return View("Index");
            }
        }

        [HttpPost]
        public ActionResult Edit(sites site)
        {
            try
            {
                db.sites.Attach(site);
                db.ObjectStateManager.ChangeObjectState(site, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (UpdateException error)
            {
                
            }
            return View(site);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            sites site = db.sites.Single(s => s.SiteID == id);
            db.sites.DeleteObject(site);
            if (db.SaveChanges() > 0)
                return Content("yes");

            return Content("");
        }

        public ActionResult Settings(int id)
        {
            return View();
        }
    }
}
